package admin

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"goadmin/models"
	"goadmin/utils"
	"net/http"
)

type LoginController struct {
	BaseController
}
type MyClaims struct {
	Uid int //自定义的属性 用于不同接口传值
	jwt.StandardClaims
}

func (con LoginController) Index(c *gin.Context) {
	c.String(200, "Api接口首页")
}

// 登录表单字段
type Login struct {
	Name     string `json:"name" binding:"required" msg:"请输入用户名"`
	Password string `json:"password" binding:"required"  msg:"请输入密码"`
}

func (con LoginController) DoLogin(c *gin.Context) {
	var json Login
	fmt.Print(json)
	// 将请求体绑定到结构体，验证参数
	//ShouldBindJSON
	if err := c.ShouldBind(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err.Error(),
			"code": http.StatusBadRequest,
		})
		return
	}
	//查询数据库，验证用户是否存在
	var adminUser models.AdminUser
	//hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(json.Password), bcrypt.DefaultCost)
	//result := models.DB.Where("name = ? and password = ?", json.Name, hashedPassword).First(&adminUser)
	result := models.DB.Where("name = ? ", json.Name).First(&adminUser)
	if result.Error != nil {
		// 处理数据库错误
		c.JSON(http.StatusOK, gin.H{"msg": "用户名或者用户密码错误!", "code": 201, "error": result.Error})
		return
	}
	fmt.Printf("用户数据: %+v\n", adminUser)
	tokenStr, err := utils.GenerateToken(adminUser.ID, adminUser.Name)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"message": "生成token失败重试",
			"code":    400,
			"msg":     "登录失败",
		})
		return
	}
	var permissions []models.RolePermissions // 注意这里应该是切片，而不是单个对象
	models.DB.Where("role_id = ?", adminUser.RoleID).Find(&permissions)
	// 提取菜单ID信息
	var menuIDs []int
	for _, perm := range permissions {
		menuIDs = append(menuIDs, perm.MenuID)
	}
	var menus []models.Menus
	models.DB.Where("id IN ?", menuIDs).Find(&menus)
	menusList := utils.ConvertMenuListToTree(menus, 0)
	fmt.Printf("用户menuIDs数据: %+v\n", menuIDs)
	c.JSON(http.StatusOK, gin.H{
		"data": gin.H{
			"menusList": menusList,
			"OAuthType": "Bearer",
			"token":     tokenStr,
			"userInfo":  adminUser,
		},
		"code": 200,
		"msg":  "登录成功",
	})

}

func (con LoginController) Captcha(c *gin.Context) {
	id, b64s, err := models.MakeCaptcha()

	if err != nil {
		fmt.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"captchaId":    id,
		"captchaImage": b64s,
	})
}
